package com.xingkeduo.business.transformation.json;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xingkeduo.pojo.dto.BaseDTO;
import com.xingkeduo.pojo.enums.ServiceEnums;
import com.xingkeduo.pojo.query.CraftsmanQO;
import com.xingkeduo.pojo.table.CraftsmanFileTO;
import com.xingkeduo.pojo.table.CraftsmanServiceTO;
import com.xingkeduo.pojo.table.CraftsmanShopTO;
import com.xingkeduo.pojo.table.CraftsmanTO;
import com.xingkeduo.pojo.table.CraftsmanTO.Status;
import com.xingkeduo.util.pojo.base.BaseJson;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.DataException;
import com.xingkeduo.util.pojo.exception.InputParamException;
import com.xingkeduo.util.tool.CommonUtil;
import com.xingkeduo.util.tool.RegularUtil;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 一线员工账户封装类
 *
 * @author 高杰
 * @time 2018年12月25日 下午1:45:17
 * @description
 */
@Component
public class CraftsmanJTO extends BaseJson {
    public static CraftsmanTO createTableForNew(String json) throws Throwable {
        CraftsmanTO table = new CraftsmanTO();
        JsonNode root = validJson(json);
        if (root == null)
            throw new InputParamException(InputParamException.Type.INVALID, "参数");

        table.setLogin(validLogin(root, YesNoEnum.YES)).setPassword(validPassword(root, YesNoEnum.NO));

        return table;
    }

    public static CraftsmanTO createTableForModify(String json) throws Throwable {
        CraftsmanTO table = new CraftsmanTO();
        JsonNode root = validJson(json);
        if (root == null)
            throw new InputParamException(InputParamException.Type.INVALID, "参数");

        table.setStatus(validStatus(root, YesNoEnum.NO)).setPassword(validPassword(root, YesNoEnum.NO));

        return table;
    }

    public static CraftsmanQO createQueryForList(String json) throws Throwable {
        CraftsmanQO query = new CraftsmanQO();
        JsonNode root = validJson(json);
        if (root == null)
            return query;

        query.setCode(validCode(root, YesNoEnum.NO)).setStatus(validStatus(root, YesNoEnum.NO));
        return query;
    }

    /**
     * 根据id,name,phone 查询发型师集合 用处:订单
     *
     * @param json:
     * @return : com.xingkeduo.pojo.query.CraftsmanQO
     * @author : gaozifeng
     * @date : 2019/7/5 16:07
     */
    public static CraftsmanQO createQueryForCondition(String json) throws Throwable {
        CraftsmanQO query = new CraftsmanQO();
        JsonNode root = validJson(json);
        if (root == null)
            return query;

        String value = null;
        if (root.has("condition")) {
            value = root.path("condition").asText().trim();
            if (RegularUtil.isPositiveInteger(value)) {
                if (value.length() != 11) {
                    query.setCode(validPrimary(root, "condition", YesNoEnum.NO));
                }
            }
        }
        return query;
    }

    //statuss
    public static CraftsmanQO createQueryForStatuss(String json) throws Throwable {
        CraftsmanQO query = new CraftsmanQO();
        JsonNode root = validJson(json);
        if (root == null)
            return query;

        query.setCode(validCode(root, YesNoEnum.NO)).setStatuss(validStatuses(root, YesNoEnum.NO)).setId(validPrimary(root, "id", YesNoEnum.NO))
                .setLeaveStatus(validLeaveStatus(root, YesNoEnum.NO));
        if (null == query.getStatuss()) {
            query.setStatus(validStatus(root, YesNoEnum.NO));
        }

        return query;
    }

    public static CraftsmanQO createQueryForLogin(String json) throws Throwable {
        CraftsmanQO query = new CraftsmanQO();
        JsonNode root = validJson(json);
        if (root == null)
            return query;

        if (root.has("accessToken")) {
            query.setLogin(validLogin(root, YesNoEnum.NO));
        } else {
            query.setLogin(validLogin(root, YesNoEnum.YES));
        }
        query.setPassword(validPassword(root, YesNoEnum.NO)).setNewLogin(validString(root, "newLogin", 50, YesNoEnum.NO));
        return query;
    }

    /**
     * 修改   密码
     *
     * @param json:
     * @return : com.xingkeduo.pojo.query.CraftsmanQO
     * @author : gaozifeng
     * @date : 2019/3/18 21:56
     */
    public static CraftsmanQO createQueryForUpdatePwd(String json) throws Throwable {
        CraftsmanQO query = new CraftsmanQO();
        JsonNode root = validJson(json);
        if (root == null)
            return query;

        query.setLogin(validLogin(root, YesNoEnum.YES)).setStatus(validStatus(root, YesNoEnum.NO)).setPassword(validString(root, "password", 32, YesNoEnum.YES))
                .setMsgCode(validString(root, "msgCode", 6, YesNoEnum.NO)).setNewPassWord(validString(root, "confirmPassWord", 32, YesNoEnum.YES));
        if (!RegularUtil.isSelfPhone(query.getLogin())) {
            throw new DataException(DataException.Type.DEFAULT, "手机号格式不正确");
        }
        if (!query.getPassword().equals(query.getNewPassWord())) {
            throw new DataException(DataException.Type.DEFAULT, "两次输入的密码不一致");
        }
        if (root.has("id")) {
            String value = root.path("id").asText().trim();
            query.setId(validId(root, YesNoEnum.NO));
        }
        return query;
    }

    /**
     * 完善信息时 只需校验密码
     *
     * @param json:
     * @return : com.xingkeduo.pojo.query.CraftsmanQO
     * @author : gaozifeng
     * @date : 2019/3/18 21:56
     */
    public static CraftsmanQO createQueryForCheckPwd(String json) throws Throwable {
        CraftsmanQO query = new CraftsmanQO();
        JsonNode root = validJson(json);
        if (root == null)
            return query;

        query.setPassword(validString(root, "password", 32, YesNoEnum.NO)).setRegisterStep(validRegisterStep(root, YesNoEnum.YES)).setNewPassWord(validString(root, "confirmPassWord", 32, YesNoEnum.NO));
        if (null != query.getPassword()) {
            if (!query.getPassword().equals(query.getNewPassWord())) {
                throw new DataException(DataException.Type.DEFAULT, "两次输入的密码不一致");
            }
        }
        return query;
    }

    public static CraftsmanQO createQueryForPrimary(String json) throws Throwable {
        CraftsmanQO query = new CraftsmanQO();
        JsonNode root = validJson(json);
        if (root == null)
            throw new InputParamException(InputParamException.Type.INVALID, "参数");

        query.setId(validId(root, YesNoEnum.YES)).setStatus(validStatus(root, YesNoEnum.NO));

        return query;
    }

    public static ObjectNode toJson(CraftsmanTO table) throws Throwable {
        ObjectNode root = MAPPER.createObjectNode();

        if (table != null) {
            if (table.getCraftsmanServiceList() != null && table.getCraftsmanServiceList().size() > 0) {
                StringBuffer serviceNames = new StringBuffer("");
                for (int i = 0; i < table.getCraftsmanServiceList().size(); i++) {
                    if (table.getCraftsmanServiceList().get(i) != null && table.getCraftsmanServiceList().get(i).getServiceId() > 0
                            && ServiceEnums.getStatus(table.getCraftsmanServiceList().get(i).getServiceId() + "") != null) {
                        if (i != 0) {
                            serviceNames.append("/");
                        }
                        serviceNames.append(ServiceEnums.getStatus(table.getCraftsmanServiceList().get(i).getServiceId() + "").getName());
                    }
                }
                root.put("serviceNames", serviceNames.toString());
            }

            if (table.getLeaveStatus() != null) {
                root.put("leaveStatus", table.getLeaveStatus().getValue());
            }
            root.put("status", table.getRegisterStep() != null ? table.getRegisterStep() : 0);
            if (table.getLogin() != null)
                root.put("login", table.getLogin());
            if (table.getType() != null) {
                root.put("type_value", table.getType().getValue());
                root.put("type_desc", table.getType().getDesc());
            }
            if (table.getStatus() != null) {
                root.put("status_value", table.getStatus().getValue());
                root.put("status_desc", table.getStatus().getDesc());
            }
            //离职时的状态
            if (null != table.getLeaveStatus()) {
                root.put("leaveStatusValue", table.getStatus().getValue());
                root.put("leaveStatusDesc", table.getStatus().getDesc());
            }
            toBaseJson(root, table);

            //图片信息
            if (table.getFiles() != null) {
                root.putPOJO("files", CraftsmanFileJTO.toJson(table.getFiles()));
            }
            //TODO 待更换成对象
            if (table.getHealthList() != null) {
                root.putPOJO("health", CraftsmanHealthJTO.toJson(table.getHealthList()));
            }
            if (null != table.getHealthTO()) {
                root.putPOJO("healthTO", CraftsmanHealthJTO.toJson(table.getHealthTO()));
            }
            if (table.getJob() != null)
                root.putPOJO("job", CraftsmanJobJTO.toJson(table.getJob()));
            if (table.getSocial() != null)
                root.putPOJO("social", CraftsmanSocialJTO.toJson(table.getSocial()));
            if (table.getDuty() != null) {
                root.putPOJO("duty", CraftsmanDutyJTO.toJson(table.getDuty()));
            }
//            if (table.getCraftsmanShop()!=null) {
//            	root.putPOJO("shop", CraftsmanShopJTO.toJson(table.getCraftsmanShop()));
//            }
            if (table.getJobseekerJobTO() != null) {
                root.putPOJO("jobseekerJob", JobseekerJobJTO.toJson(table.getJobseekerJobTO()));
            }
            if (!CommonUtil.isEmpty(table.getAssesses()))
                root.putPOJO("assesses", JobseekerAssessJTO.toJson(table.getAssesses()));
            if (!CommonUtil.isEmpty(table.getTraces()))
                root.putPOJO("traces", CraftsmanTraceJTO.toJson(table.getTraces()));
            if (table.getCraftsmanLevelTO() != null) {
                root.putPOJO("level", CraftsmanLevelJTO.toJsonCodeAndName(table.getCraftsmanLevelTO()));
            }
            if (null != table.getCompanyDTOList()) {
                root.putPOJO("company", BaseDTOJTO.toJson(table.getCompanyDTOList()));
            }
            if (null != table.getShopIds()) {
                root.putPOJO("shopIds", table.getShopIds());
            }
            if (null != table.getShopList()) {
                root.putPOJO("shops", toJsonForShop(table.getShopList()));
            }
            //后台需要的图片信息
            if (null != table.getPictureGrounp()) {
                List<CraftsmanFileTO> grounp = table.getPictureGrounp();
                for (CraftsmanFileTO file : grounp) {
                    switch (file.getType()) {
                        case "1":
                            root.put("user_pic", file.getPath() == null ? null : file.getPath());
                            break;
                        case "2":
                            root.put("idcarPositive_pic", file.getPath() == null ? null : file.getPath());
                            break;
                        case "3":
                            root.put("idcardNega_pic", file.getPath() == null ? null : file.getPath());
                            break;
                        case "4":
                            root.put("bankPositive_pic", file.getPath() == null ? null : file.getPath());
                            break;
                        case "5":
                            root.put("bankNega_pic", file.getPath() == null ? null : file.getPath());
                            break;
                        case "6":
                            root.put("healthPositive_pic", file.getPath() == null ? null : file.getPath());
                            break;
                        case "7":
                            root.put("healthNega_pic", file.getPath() == null ? null : file.getPath());
                            break;
                    }
                }

            }
            //求职者信息
            if (null != table.getJobseekerTO()) {
                root.putPOJO("jobseekerTO", JobseekerJTO.toJson(table.getJobseekerTO()));
            }
//            if (null != table.getShopDTO()) {
//                root.putPOJO("shopid", BaseDTOJTO.toJson(table.getShopDTO()));
//            }

        }

        return root;
    }

    public static ArrayNode toJsonForShop(List<BaseDTO> tables) throws Throwable {
        ArrayNode root = MAPPER.createArrayNode();

        if (!CommonUtil.isEmpty(tables))
            for (Iterator<BaseDTO> iterator = tables.iterator(); iterator.hasNext(); ) {
                root.add(BaseDTOJTO.toJson(iterator.next()));
            }

        return root;
    }

    public static ArrayNode toJson(List<CraftsmanTO> tables) throws Throwable {
        ArrayNode root = MAPPER.createArrayNode();

        if (!CommonUtil.isEmpty(tables))
            for (Iterator<CraftsmanTO> iterator = tables.iterator(); iterator.hasNext(); ) {
                root.add(toJson(iterator.next()));
            }

        return root;
    }

    public static ArrayNode toJsonOfUserServiceConfig(Map<Long, List<CraftsmanServiceTO>> map) throws Throwable {
        ArrayNode root = MAPPER.createArrayNode();

        if (map != null && map.size() > 0) {
            for (Map.Entry<Long, List<CraftsmanServiceTO>> entry : map.entrySet()) {
                root.add(toJsonOfUserServiceConfig(entry.getKey(), entry.getValue()));
            }
        }
        return root;
    }

    public static ArrayNode toJsonOfUserShops(List<CraftsmanShopTO> list) throws Throwable {
        ArrayNode root = MAPPER.createArrayNode();

        if (!CommonUtil.isEmpty(list))
            for (Iterator<CraftsmanShopTO> iterator = list.iterator(); iterator.hasNext(); ) {
                root.add(CraftsmanShopJTO.toJson(iterator.next()));
            }
        return root;
    }


    public static ObjectNode toJsonOfUserServiceConfig(Long shopid, List<CraftsmanServiceTO> toList) throws Throwable {
        ObjectNode root = MAPPER.createObjectNode();

        if (shopid != null && toList != null && toList.size() > 0) {
            root.put("shopid", shopid);
            ArrayNode toArray = MAPPER.createArrayNode();
            for (int i = 0; i < toList.size(); i++) {
                if (toList.get(i) != null) {
//        			ObjectNode to = MAPPER.createObjectNode();
//            		to.put("serviceId", toList.get(i).getServiceId());
//            		toArray.add(to);
                    toArray.add(toList.get(i).getServiceId());
                }
            }
            root.put("serviceIds", toArray);
        }

        return root;
    }


    public static String validLogin(JsonNode node, YesNoEnum isRequired) throws Throwable {
        String key = "login";
        if (YesNoEnum.YES == isRequired && !node.has(key))
            throw new InputParamException(InputParamException.Type.NULL, key);

        if (node.has(key)) {
            String value = node.path(key).asText().trim();
            if (CommonUtil.isEmpty(value) || value.length() > 50)
                throw new InputParamException(InputParamException.Type.INVALID, key + " error");
            return value;
        }
        return null;
    }

    public static String validPassword(JsonNode node, YesNoEnum isRequired) throws Throwable {
        String key = "password";
        if (YesNoEnum.YES == isRequired && !node.has(key))
            throw new InputParamException(InputParamException.Type.NULL, key);

        if (node.has(key)) {
            String value = node.path(key).asText().trim();
            if (CommonUtil.isEmpty(value) || value.length() > 32)
                throw new InputParamException(InputParamException.Type.INVALID, key + " error");
            return value;
        }
        return null;
    }

    public static Integer validRegisterStep(JsonNode node, YesNoEnum isRequired) throws Throwable {
        String key = "registerStep";
        if (YesNoEnum.YES == isRequired && !node.has(key))
            throw new InputParamException(InputParamException.Type.NULL, key);

        if (node.has(key)) {
            String value = node.path(key).asText().trim();
            if (CommonUtil.isEmpty(value) || value.length() > 2)
                throw new InputParamException(InputParamException.Type.INVALID, key + " error");
            return Integer.valueOf(value);
        }
        return null;
    }

    public static Status validStatus(JsonNode node, YesNoEnum isRequired) throws Throwable {
        String key = "status";
        if (YesNoEnum.YES == isRequired && !node.has(key))
            throw new InputParamException(InputParamException.Type.NULL, key);

        if (node.has(key)) {
            String value = node.path(key).asText().trim();
            if (!Status.validValue(value))
                throw new InputParamException(InputParamException.Type.INVALID, key + " error");
            return Status.getStatus(value);
        }
        return null;
    }

    public static Status validLeaveStatus(JsonNode node, YesNoEnum isRequired) throws Throwable {
        String key = "leaveStatus";
        if (YesNoEnum.YES == isRequired && !node.has(key))
            throw new InputParamException(InputParamException.Type.NULL, key);

        if (node.has(key)) {
            String value = node.path(key).asText().trim();
            if (!Status.validValue(value))
                throw new InputParamException(InputParamException.Type.INVALID, key + " error");
            return Status.getStatus(value);
        }
        return null;
    }


    public static Set<Status> validStatuses(JsonNode node, YesNoEnum isRequired) throws Throwable {
        String key = "statuss";
        if (YesNoEnum.YES == isRequired && !node.has(key))
            throw new InputParamException(InputParamException.Type.NULL, key);

        if (node.has(key)) {
            Set<Status> statuses = new HashSet<>();
            String value = node.path(key).asText().trim();
            String[] values = value.split(",");
            for (int i = 0; i < values.length; i++) {
                if (!CraftsmanTO.Status.validValue(values[i]))
                    throw new InputParamException(InputParamException.Type.INVALID, key + " error");
                statuses.add(Status.getStatus(values[i]));
            }
            return statuses;
        }
        return null;
    }

}
